package com.xudow.app.dynamicstate_old.data;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcelable;
import android.view.View;

import com.jude.beam.expansion.BeamBasePresenter;
import com.jude.beam.model.AbsModel;
import com.jude.utils.JUtils;
import com.xudow.app.dynamicstate_old.domain.Config;
import com.xudow.app.dynamicstate_old.domain.entity.Dynamic;
import com.xudow.app.dynamicstate_old.domain.entity.UserIntroduce;
import com.xudow.app.dynamicstate_old.domain.entity.WrapUserIntroduce;
import com.xudow.app.dynamicstate_old.module.PictureActivity;
import com.xudow.app.dynamicstate_old.module.message.LocationActivity;
import com.xudow.app.dynamicstate_old.module.user.UserProfileActivity;
import com.xudow.app.util.StringUtils;

import io.rong.message.LocationMessage;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Subscription;
import rx.functions.Action1;
import rx.subjects.BehaviorSubject;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;

import static com.baidu.location.b.k.co;
import static java.security.AccessController.getContext;

/**
 * Created by Mr.Jude on 2015/7/8.
 */
public class RongYunModel extends AbsModel {

    public static RongYunModel getInstance() {
        return getInstance(RongYunModel.class);
    }

    public BehaviorSubject<Integer> mNotifyBehaviorSubject = BehaviorSubject.create();

    public void loginOut() {
        RongIM.getInstance().logout();
    }

    public Subscription registerNotifyCount(Action1<Integer> notify) {
        return mNotifyBehaviorSubject.subscribe(notify);
    }

    public void connectRongYun1(String token) {
        JUtils.Log("token:" + token);
        RongIM.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                JUtils.Log("融云Token失效");
            }

            @Override
            public void onSuccess(String s) {
                JUtils.Log("融云连接成功");
                setRongYun();
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                JUtils.Log("融云连接失败：" + errorCode.getValue() + ":" + errorCode.getMessage());
            }
        });
        RongIMClient.setConnectionStatusListener(connectionStatus -> {
            switch (connectionStatus) {
                case CONNECTED://连接成功。
                    break;
                case DISCONNECTED://断开连接。
                    break;
                case CONNECTING://连接中。
                    break;
                case NETWORK_UNAVAILABLE://网络不可用。
                    break;
                case KICKED_OFFLINE_BY_OTHER_CLIENT://用户账户在其他设备登录，本机会被踢掉线

                    break;
            }
        });
    }

    public void setRongYun() {
        try {
            RongIM.setUserInfoProvider(userId -> {
                try {
                    JUtils.Log("get User:" + userId);
                    WrapUserIntroduce wrapUserIntroduce = DynamicModel.getInstance().getUserIntroduceLock(Integer.valueOf(userId)).execute().body();
                    if (wrapUserIntroduce != null) {
                        UserIntroduce userIntroduce = wrapUserIntroduce.getMainData();
                        return new UserInfo(userId, StringUtils.isEmpty(userIntroduce.getRemarkName()) ? userIntroduce.getUserName() : userIntroduce.getRemarkName(), Uri.parse(ImageModel.getXueDouAvatar(userIntroduce.getHeadUrl())));
                    }
                } catch (Exception e) {
                }
                return null;
            }, true);

            RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {
                @Override
                public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                    Intent i = new Intent(context, UserProfileActivity.class);
                    i.putExtra(UserProfileActivity.USER_PROFILE_ID, Long.valueOf(userInfo.getUserId()));
                    context.startActivity(i);
                    return true;
                }

                @Override
                public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {

                    return false;
                }

                @Override
                public boolean onMessageClick(Context context, View view, Message message) {
                    if (message.getContent() instanceof LocationMessage) {
                        Intent intent = new Intent(context, LocationActivity.class);
                        intent.putExtra("location", message.getContent());
                        context.startActivity(intent);
                    } else if (message.getContent() instanceof ImageMessage) {
                        ImageMessage imageMessage = (ImageMessage) message.getContent();
                        Intent i = new Intent(context, PictureActivity.class);
                        Uri uri = (imageMessage.getLocalUri() == null ? imageMessage.getRemoteUri() : imageMessage.getLocalUri());
                        i.putExtra(PictureActivity.KEY_PICTURE, uri.toString());
                        context.startActivity(i);
                    }
                    return false;
                }

                @Override
                public boolean onMessageLinkClick(Context context, String s) {
                    return false;
                }

                @Override
                public boolean onMessageLongClick(Context context, View view, Message message) {
                    return false;
                }
            });
            RongIM.getInstance().setOnReceiveUnreadCountChangedListener(i -> mNotifyBehaviorSubject.onNext(i), Conversation.ConversationType.PRIVATE);
            RongIM.setLocationProvider(new LocationProvider());
        } catch (Exception e) {
            JUtils.Log("融云出错");
        }
    }

    private RongIM.LocationProvider.LocationCallback mLastLocationCallback;

    //位置提供者
    class LocationProvider implements RongIM.LocationProvider {

        /**
         * 位置信息提供者:LocationProvider 的回调方法，打开第三方地图页面。
         *
         * @param context  上下文
         * @param callback 回调
         */
        @Override
        public void onStartLocation(Context context, LocationCallback callback) {
            setLastLocationCallback(callback);
            Intent intent = new Intent(context, LocationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }

    public RongIM.LocationProvider.LocationCallback getLastLocationCallback() {
        return mLastLocationCallback;
    }

    public void setLastLocationCallback(RongIM.LocationProvider.LocationCallback lastLocationCallback) {
        this.mLastLocationCallback = lastLocationCallback;
    }

    public void updateRongYunPersonBrief(long userId) {
        DynamicModel.getInstance().getUserInfo(userId)
                .subscribe(userIntroduce -> {
                    UserIntroduce p = userIntroduce.getMainData();
                    RongIM.getInstance().refreshUserInfoCache(new UserInfo(p.getId() + "", StringUtils.isEmpty(p.getRemarkName()) ? p.getUserName() : p.getRemarkName(), Uri.parse(ImageModel.getXueDouAvatar(p.getHeadUrl()))));
                });
    }

    public void chatPerson(Context ctx, String id, String title) {
        RongIM.getInstance().startPrivateChat(ctx, id, title);
    }

    public void chatGroup(Context ctx, String id, String title) {
        RongIM.getInstance().startGroupChat(ctx, id, title);
    }

    public void chatList(Context ctx) {
        RongIM.getInstance().startConversationList(ctx);
    }
}
